<template>
  <div class="scholarship-applications-container">
    <div class="header">
      <div class="left">
        <h2>奖学金审核</h2>
      </div>
      <div class="right">
        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索申请人/项目名称"
          style="width: 220px"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <!-- 状态筛选 -->
        <el-select 
          v-model="statusFilter" 
          placeholder="状态筛选" 
          clearable 
          style="width: 120px"
          @change="handleStatusChange"
        >
          <el-option label="待审核" value="PENDING">
            <el-tag>待审核</el-tag>
          </el-option>
          <el-option label="已通过" value="APPROVED">
            <el-tag type="success">已通过</el-tag>
          </el-option>
          <el-option label="已拒绝" value="REJECTED">
            <el-tag type="danger">已拒绝</el-tag>
          </el-option>
        </el-select>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="applications"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="申请项目" min-width="150">
          <template #default="{ row }">
            {{ row.scholarship.title }}
          </template>
        </el-table-column>
        <el-table-column label="申请学生" min-width="120">
          <template #default="{ row }">
            {{ row.student.name }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="申请理由" min-width="200" show-overflow-tooltip />
        <el-table-column prop="attachmentUrl" label="附件" width="100">
          <template #default="{ row }">
            <el-link v-if="row.attachmentUrl" type="primary" :href="`http://localhost:9090${row.attachmentUrl}`" target="_blank">
              查看
            </el-link>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'PENDING'"
              type="primary"
              size="small"
              @click="handleReview(row)"
            >
              审核
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      title="申请审核"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="approved">
          <el-radio-group v-model="form.approved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="reviewComments">
          <el-input
            v-model="form.reviewComments"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TeacherScholarshipApplicationList'
}
</script>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getApplications, reviewApplication, deleteApplication } from '@/api/teacher/scholarshipApplication'
import { formatDate } from '@/utils/format'

// 表格数据
const loading = ref(false)
const applications = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const statusFilter = ref('')
const searchQuery = ref('')

// 获取申请列表
const fetchApplications = async () => {
  try {
    loading.value = true
    const response = await getApplications({
      page: currentPage.value - 1,
      size: pageSize.value,
      status: statusFilter.value,
      search: searchQuery.value
    })
    
    if (response) {
      applications.value = response.content
      total.value = response.totalElements
    }
  } catch (error) {
    console.error('Failed to fetch applications:', error)
    ElMessage.error('获取申请列表失败')
  } finally {
    loading.value = false
  }
}

// 状态相关
const getStatusType = (status) => {
  switch (status) {
    case 'PENDING': return ''
    case 'APPROVED': return 'success'
    case 'REJECTED': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'PENDING': return '待审核'
    case 'APPROVED': return '已通过'
    case 'REJECTED': return '已拒绝'
    default: return '未知'
  }
}

// 处理状态筛选
const handleStatusChange = () => {
  currentPage.value = 1
  fetchApplications()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchApplications()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchApplications()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchApplications()
}

// 审核相关
const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)
const currentId = ref(null)

const form = ref({
  approved: null,
  reviewComments: ''
})

const rules = {
  approved: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  reviewComments: [
    { required: true, message: '请输入审核意见', trigger: 'blur' }
  ]
}

const handleReview = (row) => {
  currentId.value = row.id
  form.value = {
    approved: null,
    reviewComments: ''
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    await reviewApplication(currentId.value, form.value)
    ElMessage.success('审核成功')
    dialogVisible.value = false
    fetchApplications()
  } catch (error) {
    console.error('Review failed:', error)
    ElMessage.error(error.response?.data || '审核失败')
  } finally {
    submitting.value = false
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条申请记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteApplication(row.id)
      ElMessage.success('删除成功')
      fetchApplications()
    } catch (error) {
      console.error('Delete failed:', error)
      ElMessage.error(error.response?.data || '删除失败')
    }
  })
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchApplications()
})
</script>

<style scoped>
.scholarship-applications-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left {
  display: flex;
  align-items: center;
  gap: 16px;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

/* 添加状态标签样式 */
.el-tag {
  margin: 0;
  text-align: center;
  width: 100%;
}

/* 调整表格内容垂直对齐 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

/* 优化按钮样式 */
:deep(.el-button--small) {
  padding: 8px 16px;
}
</style> 